<?php

namespace App\Console\Commands;

use App\Constant\JpushCode;
use App\Events\JpushNoticeEvent;
use App\Events\RepayMentEvent;
use App\Events\TestBroadcastEvent;
use App\Events\TestQueueEvent;
use App\Events\WithHoldEvent;
use App\Exceptions\GeneralException;
use App\Facades\MoneyPlatformRequestFacade;
use App\Jobs\RepayCommonJob;
use App\Jobs\RepayJobQueue;
use App\Library\ArrayTools\ArrayTools;
use App\Library\Bank\BankCode;
use App\Library\String\Strings;
use App\Library\Traits\RepaySmsRemind;
use App\ModelFilters\RepaySummaryFilter;
use App\Models\Admin;
use App\Models\RepayRecord as RepayRecordModel;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\SettingRepayRate;
use App\Models\Traits\Repay;
use App\Models\User;
use App\Models\UserApplyRiskLog;
use App\Models\UserBankCard;
use App\Models\UserCertOcr;
use App\Models\UserGlobal;
use App\Models\UserInfo;
use App\Models\UserLoanRequest;
//use App\ModelTransfers\Traits\TUser;
//use App\ModelTransfers\WsLoans\LoanApply;
//use App\ModelTransfers\WsLoans\LoanOrder;
//use App\ModelTransfers\WsLoans\LoanRepay;
//use App\ModelTransfers\WsLoans\LoanVirement;
//use App\ModelTransfers\WsUsers\TUserInfos;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use MathPHP\Finance;
//use \App\ModelTransfers\Traits\Repay as TransfersRepayTrait;
use Overtrue\Pinyin\Pinyin;

class TestCommand extends Command
{
    use Notifiable, RepaySmsRemind, Repay;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test {action : test|repay|transfer|test1|test_repay}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description test';

    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Description:
     * Author: Sam
     * DateTime: 2019/1/14 11:49
     * @throws \App\Exceptions\GeneralException
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['test', 'repay', 'transfer', 'test1','test_repay'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'reptile'.");
            exit(1);
        }
    }

    protected function runAction()
    {
        $this->{$this->action}();
    }

    public function transfer()
    {
        $pid = getmypid();
        for ($i = 1; $i <= 10000; $i++) {
            try {
                $rand = rand(10000, 99999) . $pid;
                $init = [
                    'account' => 'Admin' . $rand,
                    'password' => bcrypt('123456'),
                    'mobile' => 176219 . $rand,
                    'email' => 'test' . $rand . '@test.com',
                    'post' => '职位',
                    'role' => 1,
                    'login_ip' => '0.0.0.0',
                    'login_time' => Carbon::now(),
                    'created_at'=>Carbon::now(),
                    'updated_at'=>Carbon::now(),
                ];
                $result = DB::table('admins')->insert($init);
                $id = DB::getPdo()->lastInsertId();
                Log::debug('test_transfer_log', [
                    'pid' => $pid,
                    'id' => $id,
                ]);
            } catch (\Exception $e) {
                Log::debug('test_transfer_exception', [
                    'pid' => $pid,
                    'message' => $e->getMessage(),
                ]);
            }
        }
        $this->info('transfer done');
    }

    /**
     * Description: 临时修改密码
     * Author: liChunlong
     * DateTime: 2019-04-15
     * @param ModifyPassRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function tempTestModifyPass()
    {
//        $phoneNum = $request->get('phone_num');

        $phoneNum = '13973259624';
        $password = 'a111111';
        $user = User::where('phone_num', $phoneNum)->first();
//        dd($user);
        if (!$user) {
            return failed('该用户不存在');
        }
        /*
        $key1 = 'sms_verify_phone_action_' . $phoneNum . $request->getClientIp();
        if (!Cache::get($key1)) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        $certInfo = $user->valid;
        $key2 = 'cert_verify_' . $user->id;
        $certVerify = Cache::get($key2);
        if ($certInfo && !$certVerify) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        */
//        $user->password = $request->get('n_password');
        $user->password = $password;
        if (!$user->save()) {
            return respond([], '修改密码操作失败');
        }
        dd($user);
//        Cache::forget($key1);
//        Cache::forget($key2);
        return success([]);
    }

    public function test()
    {
        dd(3);
        $user = DB::table('user_infos')->where('user_id',24)->first();
        dd(json_decode($user->phone_address_list));
        
        $sql = "SELECT
                    a.user_id ,
                    b.id as loan_id,
                    b.nfsp_user_id,
                    a.
                FROM
                    user_loan_requests a
                LEFT JOIN users b ON a.user_id = b.id
                WHERE
                    a.`status` = 9
                AND a.current = 1
                AND a.risk_status = 1
                AND b.nfsp_user_id IS NULL";
        $ret = DB::select($sql);
        foreach ($ret as $value){
            $risks = UserApplyRiskLog::where('loan_request_id', $value['loan_id'])->get();
            $loan = UserLoanRequest::find($value['loan_id']);
            $bank_card_id = $loan->cash_card_choice_id;
            $user_info_id = $loan->user_base_info_id;
            $ret = User::userSync($value['user_id'], $bank_card_id, $user_info_id, $risks->limit);
        }

    }

    public function test1()
    {
        $sql = "SELECT
                    a.id as loan_id,
                    b.id as user_id,
                    b.nfsp_user_id
                FROM
                    user_loan_requests a
                LEFT JOIN users b ON a.user_id = b.id
                WHERE
                    a.`status` = 9
                AND a.current = 1
                AND a.risk_status = 1
                AND b.nfsp_user_id IS NULL";
//        $tt = UserLoanRequest::from('user_loan_requests a')
//            ->select('')
//            ->leftJoin('users b','a.user_id', '=', 'b.id')
//            ->leftJoin('user_apply_risk_logs c','a.id', '=', 'c.loan_request_id')
//            ->where('a.`status`', 9)
//            ->where('a.current', 1)
//            ->where('a.risk_status', 1)
//            ->whereNull('nfsp_user_id')
//            ->toSql();
//print_r($tt);exit;
        $ret = DB::select($sql);
        foreach ($ret as $value){
            $risks = UserApplyRiskLog::where('loan_request_id', $value->loan_id)->first();
            if($risks){
                $loan = UserLoanRequest::find($value->loan_id);
                $bank_card_id = $loan->cash_card_choice_id;
                $user_info_id = $loan->user_base_info_id;
                echo '用户id：'.$value->user_id . "|userSync\n";
                $result = User::userSync($value->user_id, $bank_card_id, $user_info_id, $risks->limit);
                Log::debug("test-test1--------".json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }

    }

    public function test_repay()
    {
        $summary_model = RepaySummary::where('id', 14317)->select([
            'id', 'period_count', 'loan_request_id'
        ])->first();
        $repay = RepaySummary::getFrontRepayList($summary_model);
        dd($repay);

    }

    public  function getMaritalStatus($age)
    {
        if ($age <= 21) {
            return '0';
        }
        if ($age >= 22 && $age <= 25) {
            $data = [
                1 => [
                    'id' => 1,
                    'val' => '0',
                    'v' => 7,
                ],
                2 => [
                    'id' => 2,
                    'val' => '1',
                    'v' => 3,
                ],
            ];
            $key = $this->getRand($data);
            return $data[$key]['val'];
        }
        if ($age >= 26 && $age <= 30) {
            $data = [
                1 => [
                    'id' => 1,
                    'val' => '0',
                    'v' => 3,
                ],
                2 => [
                    'id' => 2,
                    'val' => '1',
                    'v' => 7,
                ],
            ];
            $key = $this->getRand($data);
            return $data[$key]['val'];
        }
        if ($age >= 31 && $age <= 40) {
            $data = [
                1 => [
                    'id' => 1,
                    'val' => '0',
                    'v' => 1,
                ],
                2 => [
                    'id' => 2,
                    'val' => '1',
                    'v' => 9,
                ],
            ];
            $key = $this->getRand($data);
            return $data[$key]['val'];
        }
        if ($age >= 41) {
            return '1';
        }
    }
    public  function getRand($data)
    {
        $arr = [];
        foreach ($data as $item) {
            $arr[$item['id']] = $item['v'];
        }

        $total = array_sum($arr);
        foreach ($arr as $key => $proCur) {
            $randNum = mt_rand(1, $total);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $total -= $proCur;
            }
        }
        return $result;
    }
    public  function createSalary($amount)
    {
        $salary = $amount*1.6;
        $salary = $salary<5000?5000:abs($salary);
        return $salary;
    }
    public  function createEmail($name)
    {
        $data = [
            1 => [
                'id' => 1,
                'val' => '@163.com',
                'v' => 33,
            ],
            2 => [
                'id' => 2,
                'val' => '@qq.com',
                'v' => 33,
            ],
            3 => [
                'id' => 3,
                'val' => '@outlook.com',
                'v' => 34,
            ],
        ];
        $key = self::getRand($data);
        $mail = $data[$key]['val'];
        return $name.$mail;
    }



    public function repay()
    {
//        $test = Storage::disk('oss');
//        $test = Storage::disk('oss')->path('frontend/cert_file/VqehSBLrF9vYN8LHQv1HvaeFXMN0bzrXab4y2g4z.jpeg');
//        Storage::disk('oss')->setVisibility('frontend/cert_file/VqehSBLrF9vYN8LHQv1HvaeFXMN0bzrXab4y2g4z.jpeg', 'public');
//        $test = Storage::disk('oss')->path('frontend/cert_file/VqehSBLrF9vYN8LHQv1HvaeFXMN0bzrXab4y2g4z.jpeg');
//        $test = Storage::disk('oss')->signUrl('frontend/cert_file/VqehSBLrF9vYN8LHQv1HvaeFXMN0bzrXab4y2g4z.jpeg');
//        $test = Storage::disk('oss')->getVisibility('backend/home_image/image/e9c581f646fec6ce8c86a4c0c9e7a1ff.png');
//        $test = Storage::disk('oss')->get('backend/home_image/image/e9c581f646fec6ce8c86a4c0c9e7a1ff.png');
//        $test = Storage::disk('oss')->signUrl('frontend/cert_file/OyaoBBzDtJluTN9NsWiahxPz3ceHO2l4aK6AOQL6.jpeg', 3153600000);
//        var_dump($test);exit;
//        $summary = RepaySummary::find(21974);
//        $test = RepaySummary::getOrderTotalMoney($summary, 4);
//        print_r($test);exit;
//        $model = RepayRecordMoney::find(69790);
//        $result = MoneyPlatformRequestFacade::getMoneyRepayResult([
//            'third_repay_id' => $model['third_repay_id'],
//            'trade_no' => $model['trade_no'],
//        ]);
//        $data = $result['data'];
//        var_dump($data);
//        exit;
//        RepayRecord::find(1);
//        $common_fines_money = 160.56;
//        $money_fines_money = 29.14;
//        if ($money_fines_money > 0) {
////            $model->money->fines_money = $money_fines_money;
////            $model->money->save();
//            DB::table('repay_record_moneys')->where('record_id', 1)->update([
//                'fines_money' => bcmul($money_fines_money, 100, 2),
//            ]);
//        }
//        if ($common_fines_money > 0) {
////            $model->common->fines_money = $common_fines_money;
////            $model->common->save();
//            DB::table('repay_record_commons')->where('record_id', 1)->update([
//                'fines_money' => bcmul($common_fines_money, 100, 2),
//            ]);
//        }
//        event(new RepayMentEvent(33));
//        $result = MoneyPlatformRequestFacade::getMoneyRepayResult([
//            'third_repay_id' => 'RR201904042222331761853664723856',
//            'trade_no' => '6fc803a394f80b63e800495f2935eb9b',
//        ]);
//        $result = strtotime($result['data']['resultRepayDate']);
//        $result = strtotime(':01');
//        $result = Carbon::createFromTimeString($result['data']['resultRepayDate'])->toDateString();
//        var_dump($result);exit;
        event(new WithHoldEvent('853318416086423', 4));
        $this->info('repay');
    }
}